from django.shortcuts import render
from django import http
from django.views.generic import View
from django.core.cache import cache
from areas.models import Areas
from meiduo_mall.utils.constants import Code


class AreasView(View):
    def get(self, request):

        # 获取area_id
        area_id = request.GET.get('area_id')
        if not area_id:
            # 获取省份

            provinces = Areas.objects.filter(parent=None).all()
            province_list = cache.get('province_list')
            if not province_list:
                province_list = []
                for province in provinces:
                    province_list.append(
                        {
                            'id': province.id,
                            'name': province.name
                        }
                    )
                cache.set('province_list', province_list, 3600 * 24 * 30)
            content = {'province_list': province_list, 'code': Code.OK}
            return http.JsonResponse(content)
        else:
            # 根据area_id 获取市或区
            areas = Areas.objects.get(id=area_id).subs.all()
            # areas = Areas.objects.filter(parent_id=area_id)
            subs = cache.get('subs_%s' % area_id)
            if not subs:
                subs = []
                for area in areas:
                    subs.append(
                        {
                            'id': area.id,
                            'name': area.name
                        }
                    )
                cache.set('subs_%s' % area_id, subs, 3600 * 24 * 2)
            sub_data = {
                'subs': subs
            }

            content = {'code': Code.OK, 'sub_data': sub_data}
            return http.JsonResponse(content)
